package com.ceic.hn.efiletransfer

import org.slf4j.LoggerFactory
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler
import org.springframework.context.annotation.Configuration
import org.springframework.scheduling.annotation.AsyncConfigurer
import org.springframework.scheduling.annotation.EnableAsync
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
import java.util.concurrent.Executor
import java.util.concurrent.ThreadPoolExecutor


@Configuration
@EnableAsync
class AsyncConfiguration : AsyncConfigurer {

    private val logger = LoggerFactory.getLogger(javaClass)

    override fun getAsyncExecutor(): Executor {
        return ThreadPoolTaskExecutor().also {
            it.setThreadNamePrefix("async-executor")
            it.corePoolSize = 4
            it.maxPoolSize = 8
            it.setQueueCapacity(512)
            it.setRejectedExecutionHandler(ThreadPoolExecutor.CallerRunsPolicy())
            it.afterPropertiesSet()
        }
    }

    override fun getAsyncUncaughtExceptionHandler(): AsyncUncaughtExceptionHandler {
        return AsyncUncaughtExceptionHandler { ex, method, params ->
            logger.error("Unexpected async error at:${method.declaringClass.name}.${method.name}, params:${params.contentToString()}", ex)
        }
    }
}